package com.zp.drug.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.common.core.constant.PriceConstants;
import com.zp.common.core.utils.DateUtils;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.common.satoken.utils.LoginHelper;
import com.zp.drug.api.bo.DrugPriceBo;
import com.zp.drug.entity.DrugPriceLog;
import com.zp.drug.entity.bo.DrugPriceLogBo;
import com.zp.drug.entity.vo.DrugPriceLogVo;
import com.zp.drug.mapper.DrugPriceLogMapper;
import com.zp.drug.service.IDrugPriceLogService;
import com.zp.system.api.RemoteUserService;
import com.zp.system.api.entity.LoginUser;
import com.zp.system.api.entity.SysUser;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 药品价表日志Service业务层处理
 *
 * @author zhang peng
 * @ date 2023-06-16
 */
@RequiredArgsConstructor
@Service
public class DrugPriceLogServiceImpl implements IDrugPriceLogService {

    private final DrugPriceLogMapper baseMapper;
    @DubboReference
    private RemoteUserService apiUserService;

    /**
     * 查询药品价表日志
     */
    @Override
    public DrugPriceLogVo queryById (String id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询药品价表日志列表(分页)
     */
    @Override
    public TableDataInfo<DrugPriceLogVo> queryPageList (DrugPriceLogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DrugPriceLog> lqw = buildQueryWrapper(bo);
        // 获取用户list信息
        List<SysUser> sysUserList = apiUserService.getSysUserList(bo.getOrgId());
        Page<DrugPriceLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(item -> {
            List<SysUser> userList = sysUserList.stream().filter(user ->
                    StringUtils.equals(user.getUserId(),item.getCreateBy())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(userList)) {
                item.setCreateBy(userList.get(0).getNickName());
            }
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询药品价表日志列表(不分页)
     */
    @Override
    public List<DrugPriceLogVo> queryList (DrugPriceLogBo bo) {
        LambdaQueryWrapper<DrugPriceLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DrugPriceLog> buildQueryWrapper (DrugPriceLogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DrugPriceLog> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getDrugInfoId()), DrugPriceLog::getDrugInfoId, bo.getDrugInfoId());
        lqw.eq(StringUtils.isNotBlank(bo.getDrugPriceId()), DrugPriceLog::getDrugPriceId, bo.getDrugPriceId());
        lqw.eq(StringUtils.isNotBlank(bo.getMedicalInsuranceType()), DrugPriceLog::getMedicalInsuranceType, bo.getMedicalInsuranceType());
        lqw.eq(StringUtils.isNotBlank(bo.getPriceId()), DrugPriceLog::getPriceId, bo.getPriceId());
        lqw.eq(StringUtils.isNotBlank(bo.getPackageSpec()), DrugPriceLog::getPackageSpec, bo.getPackageSpec());
        lqw.eq(StringUtils.isNotBlank(bo.getPackageUnits()), DrugPriceLog::getPackageUnits, bo.getPackageUnits());
        lqw.eq(bo.getNetworkPrice() != null, DrugPriceLog::getNetworkPrice, bo.getNetworkPrice());
        lqw.eq(bo.getTradePrice() != null, DrugPriceLog::getTradePrice, bo.getTradePrice());
        lqw.eq(bo.getRetailPrice() != null, DrugPriceLog::getRetailPrice, bo.getRetailPrice());
        lqw.eq(bo.getStartDate() != null, DrugPriceLog::getStartDate, bo.getStartDate());
        lqw.eq(bo.getStopDate() != null, DrugPriceLog::getStopDate, bo.getStopDate());
        lqw.eq(StringUtils.isNotBlank(bo.getClassOnRcpt()), DrugPriceLog::getClassOnRcpt, bo.getClassOnRcpt());
        lqw.eq(StringUtils.isNotBlank(bo.getClassOnInp()), DrugPriceLog::getClassOnInp, bo.getClassOnInp());
        lqw.eq(StringUtils.isNotBlank(bo.getClassOnReckoning()), DrugPriceLog::getClassOnReckoning, bo.getClassOnReckoning());
        lqw.eq(StringUtils.isNotBlank(bo.getSubjCode()), DrugPriceLog::getSubjCode, bo.getSubjCode());
        lqw.eq(StringUtils.isNotBlank(bo.getClassOnMr()), DrugPriceLog::getClassOnMr, bo.getClassOnMr());
        lqw.eq(bo.getPriceMax() != null, DrugPriceLog::getPriceMax, bo.getPriceMax());
        lqw.eq(StringUtils.isNotBlank(bo.getIsNew()), DrugPriceLog::getIsNew, bo.getIsNew());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgId()), DrugPriceLog::getOrgId, bo.getOrgId());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), DrugPriceLog::getRemarks, bo.getRemarks());
        lqw.eq(bo.getRatio() != null, DrugPriceLog::getRatio, bo.getRatio());
        lqw.eq(StringUtils.isNotBlank(bo.getOperationType()), DrugPriceLog::getOperationType, bo.getOperationType());
        lqw.like(StringUtils.isNotBlank(bo.getDrugCode()), DrugPriceLog::getDrugCode, bo.getDrugCode());
        lqw.like(StringUtils.isNotBlank(bo.getDrugName()), DrugPriceLog::getDrugName, bo.getDrugName());
        return lqw;
    }

    /**
     * 新增药品价表日志
     */
    @Override
    public Boolean insertByBo (DrugPriceLogBo bo) {
        DrugPriceLog add = BeanUtil.toBean(bo, DrugPriceLog.class);
        validEntityBeforeSave(add);
        add.initEntity();
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改药品价表日志
     */
    @Override
    public Boolean updateByBo (DrugPriceLogBo bo) {
        DrugPriceLog update = BeanUtil.toBean(bo, DrugPriceLog.class);
        update.updateInfo();
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave (DrugPriceLog entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除药品价表日志
     */
    @Override
    public Boolean deleteWithValidByIds (Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 药品价表停价、调价 业务处理
     *
     * @param bo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean initDrugPriceListLog (DrugPriceBo bo) {
        DrugPriceLogBo drugPriceLogBo = BeanUtil.toBean(bo, DrugPriceLogBo.class);
        LoginUser loginUser = LoginHelper.getLoginUser();
        drugPriceLogBo.setDrugPriceId(bo.getId());
        drugPriceLogBo.setCreateBy(loginUser.getNickName());
        drugPriceLogBo.setCreateTime(DateUtils.getNowDate());
        drugPriceLogBo.setIsNew(PriceConstants.IS_NEW_YES);
        drugPriceLogBo.setId("");
        switch (bo.getOperationType()) {
            case PriceConstants.OPERATION_TYPE_INSERT:
                // 新增
                break;
            case PriceConstants.OPERATION_TYPE_EDIT:
                // 修改
                break;
            case PriceConstants.OPERATION_TYPE_PRICEADJUSTMENT:
                // 调价
                // 获取已存在的记录
//                List<PriceListLog> priceListLogList = getPriceListLog(bo);
//                if (CollectionUtil.isNotEmpty(priceListLogList)) {
//                    // 循环修改 是否最新价格 字段为 否
//                    priceListLogList.forEach(item -> {
//                        if (item.getStopDate() == null) {
//                            item.setIsNer(PriceConstants.IS_NER_NO);
//                            item.setStopDate(bo.getStartDate());
//                            item.setUpdateBy(loginUser.getNickName());
//                            item.setUpdateTime(DateUtils.getNowDate());
//                            drugPriceLogMapper.updateById(item);
//                        }
//                    });
//                }
                break;
            case PriceConstants.OPERATION_TYPE_STOPPRICE:
                // 停价
                // 获取已存在的记录
//                List<PriceListLog> priceListLogListStop = getPriceListLog(bo);
//                if (CollectionUtil.isNotEmpty(priceListLogListStop)) {
//                    priceListLogListStop.forEach(item -> {
//                        if (item.getStopDate() == null) {
//                            item.setStopDate(bo.getStopDate());
//                            item.setIsNer(PriceConstants.IS_NER_NO);
//                            item.setUpdateBy(loginUser.getNickName());
//                            item.setUpdateTime(DateUtils.getNowDate());
//                            drugPriceLogMapper.updateById(item);
//                        }
//                    });
//                }
                drugPriceLogBo.setStopDate(DateUtils.getNowDate());
                drugPriceLogBo.setUpdateBy(loginUser.getNickName());
                drugPriceLogBo.setIsNew(PriceConstants.IS_NEW_NO);
                break;
            case PriceConstants.OPERATION_TYPE_ENABLE:
                // 启用
//                drugPriceLogBo.setOperationType(PriceConstants.IS_NER_YES);
                break;
            case PriceConstants.OPERATION_TYPE_DELETE:
                // 删除
                drugPriceLogBo.setOperationType(PriceConstants.IS_NEW_NO);
                break;
            case PriceConstants.OPERATION_TYPE_OTHER:
                // 其他
                break;
            default:
                break;
        }
        return this.insertByBo(drugPriceLogBo);
    }

}
